package org.example.forum.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import net.minidev.asm.ASMUtil;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.config.AppConfig;
import org.example.forum.model.User;
import org.example.forum.service.IUserService;
import org.example.forum.utils.MD5Util;
import org.example.forum.utils.OSSUtil;
import org.example.forum.utils.StringUtil;
import org.example.forum.utils.UUIDUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    /**
     * 用户注册
     * @param username 用户名
     * @param nickname 用户昵称
     * @param password 密码
     * @param passwordRepeat 确认密码
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        //校验两次密码
        if(!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failure(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        String salt= UUIDUtil.UUID_32();
        user.setSalt(salt);
        String ciphertext = MD5Util.md5(password,salt);
        user.setPassword(ciphertext);
        userService.createNormalUser(user);
        return AppResult.success(ResultCode.SUCCESS);
    }


    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request, @NonNull String username, @NonNull String password) {
        //1、调用 service 方法返回 User 对象
        User user = userService.login(username, password);
        //在 service 逻辑里面已经有了抛出异常
        if(user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failure(ResultCode.FAILED_LOGIN);
        }
        //2、存储到 session 作用域里面去
        HttpSession session=request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        //3、返回结果
        return AppResult.success();
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request, @RequestParam(value = "id", required = false) Long id) {
        User user = null;
        if (id == null) {
            //1、如果 id 为空，从 session 里面获取信息 即获取当前登录用户的详情
            //不主动创建session
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
                return AppResult.failure(ResultCode.FAILED_UNAUTHORIZED);
            }
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            //2、如果 id 不为空，从数据库里面获取信息
            user = userService.selectById(id);
        }
        if (user == null) {
            return AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    @ApiOperation("退出登录")
    @GetMapping("logout")
    public AppResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(session == null) {
            log.info("退出成功");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                String username,
                                String nickname,
                                Byte gender, String email,
                                String phoneNum, String remark) {
        if(StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname) && StringUtil.isEmpty(email)
          && StringUtil.isEmpty(phoneNum) && StringUtil.isEmpty(remark) && gender==null ) {
            return AppResult.failure("您并未做出任何修改");
        }
        //封装
        User updateUser = new User();
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        //调用service
        userService.modifyInfo(updateUser);
        //更新后查询最新的用户信息
        user = userService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success(user);
    }

    @ApiOperation("修改用户密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,@NonNull String oldPassword,@NonNull String newPassword,@NonNull String repeatPassword) {
        if(!newPassword.equals(repeatPassword)) {
            return AppResult.failure(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        HttpSession session = request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        userService.modifyPassword(user.getId(), oldPassword, newPassword);
        //销毁session
        if(session!=null) {
            session.invalidate();
        }
        return AppResult.success();
    }


    @ApiOperation("修改用户头像")
    @PostMapping("/modifyAvatar")
    public AppResult modifyAvatar(HttpServletRequest request, @NonNull MultipartFile file) throws Exception {
        String OriginalFilename = file.getOriginalFilename();
        String filename = UUID.randomUUID().toString()+ OriginalFilename.substring(OriginalFilename.lastIndexOf("."));
        //file.transferTo(new File("F:\\testfile\\"+filename));
        String url= OSSUtil.uploadFile(filename,file.getInputStream());
        HttpSession session = request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        userService.modifyAvatar(user.getId(), url);
        return AppResult.success(url);
    }


}
